package cn.liuweiwei.service.impl;

import cn.liuweiwei.domain.Blog;
import cn.liuweiwei.domain.Type;
import cn.liuweiwei.mapper.BlogMapper;
import cn.liuweiwei.mapper.TypeMapper;
import cn.liuweiwei.service.TypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private BlogMapper blogMapper;

    @Override
    public PageInfo<Type> findAllTypeByPage(String pageNum, String pageSize) {
        PageHelper.startPage(parseString(pageNum), parseString(pageSize));
        List<Type> typeList = initBlogCountByTypeId();
        return new PageInfo<>(typeList);
    }

    private List<Type> initBlogCountByTypeId() {
        List<Type> typeList = typeMapper.findAll();
        for (Type type : typeList) {
            type.setBlogCount(blogMapper.findBlogCountByTypeId(type.getId().toString()));
        }
        return typeList;
    }

    @Override
    public Type findBlogsByTypeId(String id) {
        Type type = typeMapper.findOneById(id);
        List<Blog> blogList = blogMapper.findBlogsByTypeId(id);
        type.setBlogList(blogList);

        for (Blog blog : blogList) {
            Type newType = new Type();
            newType.setId(type.getId());
            newType.setTypeName(type.getTypeName());
            blog.setType(newType);
        }

        return type;
    }

    @Override
    @Transactional
    public void insertOneType(Type type) {
        typeMapper.insertOne(type);
    }

    @Override
    @Transactional
    public void updateOneType(Type type) {
        typeMapper.update(type);
    }

    @Override
    @Transactional
    public void deleteOneType(String id) {
        typeMapper.deleteById(id);
    }

    @Override
    public List<Type> findAllType() {
        return initBlogCountByTypeId();
    }

    private Integer parseString(String str) {
        return Integer.parseInt(str);
    }

}
